import React, { useEffect, useState } from 'react'
import {
  Card,
  Table,
  Pagination,
  Tag,
  Button,
  Tree,
  Row,
  Col,
  message,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import type { DataNode, TreeProps } from 'antd/es/tree'
import { useParams } from 'react-router-dom'
import {
  regGetDepList,
  regGetScheduleRules,
  regGetScheduleDetail,
} from '@api/hospital/hospitalList'
import {
  IdepList,
  IScheduleRuleList,
  IscheduleDetailList,
  IsheduleDetail,
} from '@api/hospital/hospitalList/model/hospitalListTypes'

let depcode: string //记录当前科室的编码
export default function HospitalSchedule() {
  const { hoscode } = useParams()

  // 所有科室数据
  const [depList, setDepList] = useState<IdepList>([])
  // 所有一级科室的depcode
  const [depCodes, setDepCodes] = useState<string[]>([])

  // 排班规则数据
  const [scheduleRule, setScheduleRule] = useState<IScheduleRuleList>([])

  // 排班对应的分页数据
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(0)

  // 面包屑相关数据
  const [hosname, setHosname] = useState('')
  const [depname, setDepname] = useState('')
  const [workDate, setWorkDate] = useState('')

  // 排班详情数据
  const [scheduleDetail, setScheduleDetail] = useState<IscheduleDetailList>([])

  useEffect(() => {
    // 获取医院所有科室数据
    getDepList()
  }, [])

  // 获取科室数据
  async function getDepList() {
    const result = await regGetDepList(hoscode as string)
    // console.log(result)
    // 往所有的一级科室对象中添加disabled:true这个字段
    result.forEach((item) => {
      item.disabled = true
    })
    setDepList(result)
    setDepCodes(
      result.map((item) => {
        return item.depcode
      })
    )
    setDepname(result[0].children[0].depname)

    depcode = result[0].children[0].depcode
    getScheduleRule(1, 5, depcode)
  }

  // 获取排班规则数据
  async function getScheduleRule(
    page: number,
    pageSize: number,
    depcode: string
  ) {
    const result = await regGetScheduleRules(
      page,
      pageSize,
      hoscode as string,
      depcode
    )
    // console.log(result)
    setScheduleRule(result.bookingScheduleList)
    setTotal(result.total)
    setHosname(result.baseMap.hosname)
    setWorkDate(result.bookingScheduleList[0]?.workDate)
    if (result.bookingScheduleList[0]) {
      getScheduleDetail(result.bookingScheduleList[0]?.workDate)
    } else {
      message.error('暂无数据')
    }
  }

  // 获取排班详情
  async function getScheduleDetail(workDate: string) {
    const result = await regGetScheduleDetail(
      hoscode as string,
      depcode,
      workDate
    )
    setScheduleDetail(result)
  }

  const onSelect: TreeProps['onSelect'] = (selectedKeys, info: any) => {
    console.log('selected', selectedKeys, info)
    // 修改面包屑的depname
    setDepname(info.node.depname)
    // 获取排班规则
    depcode = selectedKeys[0] as string
    getScheduleRule(1, pageSize, depcode)
    setPage(1)
  }

  const columns: ColumnsType<IsheduleDetail> = [
    {
      title: '序号',
      render(a, b, index) {
        return index + 1
      },
    },
    {
      title: '职称',
      dataIndex: 'title',
    },
    {
      title: '号源时间',
      dataIndex: 'workDate',
    },
    {
      title: '可预约数',
      dataIndex: 'availableNumber',
    },
    {
      title: '剩余预约数',
      dataIndex: 'reservedNumber',
    },
    {
      title: '挂号费(元)',
      dataIndex: 'amount',
    },
    {
      title: '擅长技能',
      dataIndex: 'skill',
    },
  ]

  // 动态计算树结构父盒子的高度
  const height = document.documentElement.clientHeight - 64 - 34 - 48 - 14
  return (
    <Card>
      <p>
        选择：{hosname} / {depname} / {workDate}
      </p>
      {/* gutter是每一列的间隔 20表示20px */}
      <Row gutter={20}>
        {/* span表示这一列在一行中占多少份 */}
        <Col
          span={5}
          style={{ border: '1px solid #ccc', overflow: 'auto', height }}
        >
          <Tree
            // checkable // 是否展示复选框
            // 默认展示的节点的key值
            // defaultExpandedKeys={['0-0-0', '0-0-1']}
            // 默认选中选中的节点的key值
            // defaultSelectedKeys={['0-0-0', '0-0-1']}
            // defaultCheckedKeys={['0-0-0', '0-0-1']}
            onSelect={onSelect} // 选中节点
            // onCheck={onCheck} // 切换节点的复选框
            // 树结构中要渲染的数据
            treeData={depList as any}
            // 注意: 默认Tree组件动态的渲染数据中的title值,但是我们的数据中没有title,所以要告诉Tree组件,应该使用depname渲染
            fieldNames={{
              title: 'depname',
              key: 'depcode',
            }}
            // 让节点展示的属性,里面传入数组,数组里面是要展开的节点的key值.其实就是depcode值
            // 注意: 展开之后就收不起来了
            expandedKeys={depCodes}
          />
        </Col>
        <Col span={19}>
          {scheduleRule.map((item) => (
            <Tag
              key={item.workDate}
              color={item.workDate === workDate ? 'green' : ''}
              onClick={() => {
                setWorkDate(item.workDate)
                getScheduleDetail(item.workDate)
              }}
            >
              <div>{item.workDate}</div> {item.dayOfWeek} {item.availableNumber}
              / {item.reservedNumber}
            </Tag>
          ))}

          <Pagination
            total={total}
            current={page}
            pageSize={pageSize}
            showSizeChanger={true}
            style={{ marginTop: 10, marginBottom: 10 }}
            onChange={(page, pageSize) => {
              setPage(page)
              setPageSize(pageSize)
              // 请求排班规则
              getScheduleRule(page, pageSize, depcode)
            }}
          ></Pagination>
          <Table
            columns={columns}
            dataSource={scheduleDetail}
            rowKey="id"
            pagination={false}
          ></Table>
          <Button style={{ marginTop: 10 }}>返回</Button>
        </Col>
      </Row>
    </Card>
  )
}
